package com.example.myapplication.viewmodel

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.data.model.BreadcrumbItem
import com.example.myapplication.data.model.StorageItem
import com.example.myapplication.data.model.StorageSpace
import com.example.myapplication.data.repository.StorageItemRepository
import com.example.myapplication.data.repository.StorageSpaceRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

data class ItemDetailUiState(
    val item: StorageItem? = null,
    val breadcrumbs: List<BreadcrumbItem> = emptyList(),
    val isLoading: Boolean = true,
    val errorMessage: String? = null,
    val isMoveDialogVisible: Boolean = false,
    val allSpaces: List<StorageSpace> = emptyList()
)

sealed class NavigationEvent {
    data class NavigateToSpace(val spaceId: String) : NavigationEvent()
    object NavigateBack : NavigationEvent()
}

@HiltViewModel
class ItemDetailViewModel @Inject constructor(
    private val itemRepository: StorageItemRepository,
    private val spaceRepository: StorageSpaceRepository,
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {

    private val _uiState = MutableStateFlow(ItemDetailUiState())
    val uiState: StateFlow<ItemDetailUiState> = _uiState.asStateFlow()

    private val _navigationEvent = MutableSharedFlow<NavigationEvent>()
    val navigationEvent = _navigationEvent.asSharedFlow()

    init {
        viewModelScope.launch {
            spaceRepository.getAllSpaces().collect { spaces ->
                _uiState.update { it.copy(allSpaces = spaces) }
            }
        }
    }

    fun loadItemDetails(itemId: String) {
        if (itemId.isEmpty()) {
            _uiState.update { it.copy(isLoading = false, errorMessage = "无效的物品ID") }
            return
        }
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true) }
            itemRepository.getItemByIdFlow(itemId).collect { item ->
                if (item != null) {
                    getBreadcrumbs(item.spaceId)
                    _uiState.update { it.copy(item = item, isLoading = false) }
                } else {
                    _uiState.update { it.copy(isLoading = false, errorMessage = "找不到物品") }
                }
            }
        }
    }

    private suspend fun getBreadcrumbs(spaceId: String) {
        val breadcrumbs = mutableListOf<BreadcrumbItem>()
        breadcrumbs.add(BreadcrumbItem(id = "root", name = "主页"))
        var currentSpace = spaceRepository.getSpaceById(spaceId)
        while (currentSpace != null) {
            breadcrumbs.add(BreadcrumbItem(currentSpace.id, currentSpace.name))
            currentSpace = currentSpace.parentId?.let { spaceRepository.getSpaceById(it) }
        }
        // 设置最后一个为isLast = true
        if (breadcrumbs.isNotEmpty()) {
            breadcrumbs[breadcrumbs.size - 1] = breadcrumbs.last().copy(isLast = true)
        }
        _uiState.update { it.copy(breadcrumbs = breadcrumbs) }
    }

    fun onMoveClicked() {
        _uiState.update { it.copy(isMoveDialogVisible = true) }
    }

    fun onMoveDialogDismiss() {
        _uiState.update { it.copy(isMoveDialogVisible = false) }
    }

    fun migrateItem(destinationSpaceId: String) {
        val itemId = uiState.value.item?.id ?: return
        viewModelScope.launch {
            try {
                itemRepository.migrateItem(itemId, destinationSpaceId)
                onMoveDialogDismiss()
                _navigationEvent.emit(NavigationEvent.NavigateToSpace(destinationSpaceId))
            } catch (e: Exception) {
                _uiState.update { it.copy(errorMessage = "迁移失败: ${e.message}") }
            }
        }
    }
}